package service

import (
	//"fmt"
	"gin/TEST01/entity"
	"gin/common"
	"gin/common/constant"
	"gin/common/db/config"
	"gin/common/util"
	sysEntity "gin/system/entity"
	sysUtil "gin/system/util"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

//新增用户
func AddUser(c *gin.Context, loginBody *sysEntity.LoginBody) []map[string]interface{} {
	var resultList []map[string]interface{}
	err := config.GormDb.Model(&sysEntity.LoginBody{}).Table("sys_user ").Create(loginBody).Error

	// 检查添加操作是否成功
	if err != nil {
		common.ReturnError(c, constant.ERRORCODE(), "操作失败", err, int64(len(resultList)))
		log.Println("新增数据发生异常，异常信息为：  " + util.MapToJson(err))
		panic("")
		return resultList
	}
	return nil
}

//JWT 解析token
func GetProfile(c *gin.Context) []map[string]interface{} {
	var resultList []map[string]interface{}
	tokeString := c.GetHeader("Token")
	if tokeString == "" {
		common.ReturnError(c, constant.ERRORCODE(), "token不能为空，请联系开发人员处理！", "", int64(len("")))
		panic("")
	}

	//TODO

	//用户账号
	userErr := config.GormDb.Model(&entity.SysUserEntity{}).Table("sys_user as user").Select("user.user_id as userId",
		"user.user_name as userName", "user.nick_name nickName",
		"dept.dept_id as deptId", "dept.dept_name as deptName", "dept.parent_id as deptParentId", "dept.ancestors AS deptAncestors").
		Joins("LEFT JOIN sys_dept as dept on user.dept_id = dept.dept_id").Where("LOWER(user_name) = LOWER(?)", "userName").Scan(&resultList).Error
	if userErr != nil {
		common.ReturnError(c, constant.ERRORCODE(), "登录用户数据库查询失败", "", int64(len("")))
		panic("")
	}
	return resultList
}

func GetProfile1(c *gin.Context) *sysEntity.SysUser {
	sysUserEntity := &sysEntity.SysUserEntity{}
	var resultList []map[string]interface{}

	tokeString := c.GetHeader("Token")
	if tokeString == "" {
		common.ReturnError(c, constant.ERRORCODE(), "token不能为空，请联系开发人员处理！", "", int64(len("")))
		panic("")
	}

	claims, err := sysUtil.ParseJwtToken(tokeString)
	if claims == nil {
		common.ReturnError(c, constant.ERRORCODE(), "登录状态过期，请重新登录！", "", int64(len("")))
		panic("")
	}

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    1005,
			"message": "token解析错误",
		})
		c.Abort()
	}

	//用户账号
	userErr := config.GormDb.Model(&entity.SysUserEntity{}).Table("sys_user as user").Select("user.user_id as userId",
		"user.user_name as userName", "user.nick_name nickName",
		"dept.dept_id as deptId", "dept.dept_name as deptName", "dept.parent_id as deptParentId", "dept.ancestors AS deptAncestors").
		Joins("LEFT JOIN sys_dept as dept on user.dept_id = dept.dept_id").Where("LOWER(user_name) = LOWER(?)", claims.UserName).Scan(&resultList).Error
	if userErr != nil {
		common.ReturnError(c, constant.ERRORCODE(), "登录用户数据库查询失败", "", int64(len("")))
		panic("")
	}

	if len(resultList) > 0 {
		// 假设返回的切片中第一条记录就是我们要获取userName值的记录
		userName := resultList[0]["userName"].(string)
		userId := resultList[0]["userId"].(int64)
		sysUserEntity.UserName = userName
		sysUserEntity.UserId = userId
	} else {
		// 如果切片为空，说明没有查询到相关用户资料，可以进行相应的错误处理
		common.ReturnError(c, constant.ERRORCODE(), "登录用户账号信息查询错误，请联系管理员处理！", "", int64(len("")))
	}
	userId := resultList[0]["userId"].(int64)

	sysUser := new(sysEntity.SysUser)
	sysUser.FindOne(userId)
	sysUser.Token = tokeString

	sysUser.Uuid = claims.Uuid
	return sysUser
}

/***
用户查询列表
*/
func GetUserList(c *gin.Context) {
	sysUserlist := make([]*sysEntity.SysUser, 0)
	//根据解析token中的用户账号，查询用户 id,用户详细信息，以及用户所在部门信息
	userErr := config.GormDb.Model(&sysEntity.SysUser{}).Table("sys_user as user").Select("user.user_id as userId",
		"user.user_id", "user.dept_id", "user.user_name", "user.nick_name", "user.email", "user.avatar",
		"user.phonenumber", "user.password", "user.sex", "user.status", "user.del_flag", "user.login_ip", "user.login_date",
		"user.create_by", "user.create_time", "user.remark",
		"IFNULL(dept.dept_id, user.dept_id) as dept_id",
		"dept.parent_id", "dept.dept_name", "dept.order_num",
		"dept.leader", "dept.status as dept_status").
		Joins("LEFT JOIN sys_dept as dept on user.dept_id = dept.dept_id").Where("LOWER(1) = LOWER(?)", 1).Scan(&sysUserlist).Error
	if userErr != nil {
		common.ReturnError(c, constant.ERRORCODE(), constant.ERRORMSG, "", int64(len("")))
		panic("")
	}
	common.ReturnListSucess(c, constant.SUCCESSCODE(), constant.SUCCESSMSG(), sysUserlist, int64(len(sysUserlist)))
}
